package leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  出现频率最高的前K得字符串
 */
public class TopKFrequent {
    public static void main(String[] args) {
//        String[] strs = {"i", "love", "leetcode", "i", "love", "coding"};
        String[] strs={"the","day","is","sunny","the","the","the","sunny","is","is"};
        List<String> strings = topKFrequent(strs, 3);
        strings.forEach(System.out::println);
    }

    //1.声明一个map存储字符数组
    //2.将map遍历保存到list数据中
    //3.对list数组进行排序
    //4.取出前k个
    public static List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> count = new HashMap<>();
        for (String word : words) {
            count.put(word, count.getOrDefault(word, 0) + 1);
        }
        List<String> res = new ArrayList();
        res.addAll(count.keySet());
        res.sort((o1, o2) -> count.get(o1).equals(count.get(o2)) ? o1.compareTo(o2) : count.get(o2) - count.get(o1));


        return res.subList(0,k);
    }
}
